from simpy import Resource, Environment

from x_pc.core import Device, DeviceCost, System
from x_pc.model.model import Task


class ZHC(Device, DeviceCost):
    """
    303 综合拆板站台
    综合拆(ZHC)
    """
    TIME_COST = 30
    # 资源
    resource: Resource = None

    def __init__(self, env: Environment, name: str):
        super().__init__(env, name)
        self.resource = Resource(env)

    def cost(self, *args, **kwargs) -> float:
        return self.TIME_COST


class ZHCSystem(System):
    """
    综合拆板站台 系统
    """
    # TODO: 综合拆板站台 数量
    ZHC_NUMS = 2
    # ZHC列表
    zhc_list: list[ZHC] = list()

    def __init__(self, env: Environment, name: str, code: str = None):
        super().__init__(env, name, code)
        self.__init_zhc_list()

    def __init_zhc_list(self):
        self.zhc_list = [ZHC(self.env, f'综合拆-{_ + 1}') for _ in range(self.ZHC_NUMS)]

    def run_task(self, task: Task):
        if not self.zhc_list:
            while self.running:
                yield self.env.timeout(1)
                if self.zhc_list:
                    break
        #
        zhc = self.zhc_list.pop(0)
        with zhc.resource.request() as req:
            yield req
            process = task.process
            #
            process.begin_ts = self.env.now
            yield self.env.timeout(zhc.cost())
            process.end_ts = self.env.now
            process.device_code = zhc.name
            # TODO: 根据任务类型 将任务分发至不同设备
            process.device_code = None
        self.zhc_list.append(zhc)
